package com.totoro.tygeneratedragonblock.handler;

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.totoro.tygeneratedragonblock.TyGenerateDragonBlock;
import com.totoro.tygeneratedragonblock.pojo.BlockDefinition;

import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Totoro
 * @version 0.1.0
 * @date 2025/8/10 - 21:11
 * @description GameProfile缓存处理器
 **/
public class GameProfileCacheHandler {

    private final TyGenerateDragonBlock plugin;
    
    private final Map<String, GameProfile> profileCache = new ConcurrentHashMap<>();
    
    public GameProfileCacheHandler(TyGenerateDragonBlock plugin) {
        this.plugin = plugin;
        preInitAllBlocksCache();
    }

    public void clearCache() {
        profileCache.clear();
    }
    
    /**
     * @author totoro
     * @description 初始化所有方块的缓存
     * @date  21:18
     * @param []
     * @return void
     **/
    public void preInitAllBlocksCache() {
        Collection<BlockDefinition> blockDefinitions = plugin.getBlocksManager().getBlockDefinitions().values();
        for (BlockDefinition blockDefinition : blockDefinitions) {
            getCachedProfile(blockDefinition);
        }
    }
    
    /**
     * @author totoro
     * @description 返回指定方块的GameProfile，如果没有命中缓存则获取并存储返回
     * @date  21:21
     * @param [blockDefinition]
     * @return com.mojang.authlib.GameProfile
     **/
    public GameProfile getCachedProfile(BlockDefinition blockDefinition) {
        GameProfile profile = profileCache.get(blockDefinition.getId());
        if (profile == null) {
            synchronized (profileCache) {
                profile = profileCache.get(blockDefinition.getId());
                if (profile == null) {
                    profile = createGameProfile(blockDefinition);
                    if (profile != null) {
                        profileCache.put(blockDefinition.getId(), profile);
                    }
                }
            }
        }
        return profile;
    }

    private GameProfile createGameProfile(BlockDefinition blockDefinition) {
        try {
            GameProfile profile = new GameProfile(UUID.fromString("014df015-7eba-4ad0-a0e0-83164b7a45f2"), blockDefinition.getBlockName());
            profile.getProperties().put("textures", new Property("textures", blockDefinition.getMatch()));
            return profile;
        } catch (Exception e) {
            return null;
        }
    }
}
